import { userLogin, getInfo } from '@/api/user'

const state = {
  token: JSON.parse(localStorage.getItem('house-token')) || '',
  profile: JSON.parse(localStorage.getItem('house')) || {}
}
const mutations = {
  setToken(state, data) {
    state.token = data
    localStorage.setItem('house-token', JSON.stringify(data))
  },
  setProfile(state, data) {
    state.profile = data
  },
  delUser(state) {
    state.token = ''
    state.profile = {}
    localStorage.removeItem('house-token')
    localStorage.removeItem('house')
    localStorage.removeItem('house-token')
  }
}
const actions = {
  async login(store, data) {
    // 登录页应该将用户填写手机号和密码作为 data 传入
    const res = await userLogin(data)
    // console.log(res.data.data);
    store.commit('setToken', res.data.jwt)
    localStorage.setItem('house-token', JSON.stringify(res.data.jwt))
  },
  async getInfo(store) {
    const res = await getInfo()
    localStorage.setItem('house', JSON.stringify(res.data))
    store.commit('setProfile', res.data)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
